package cn.leedsoft.and.crimeintent.controller.crime_intent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.*;
import android.widget.*;
import cn.leedsoft.and.crimeintent.R;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 关于相机，还是建议，使用隐式Intent
 */
@Deprecated
public class CrimeCameraFragment extends Fragment {
    public static final String TAG = "CrimeCameraFragment";
    private SurfaceView mSurfaceView;
    private Button mTakeBtn;
    private Camera mCamera;
    private FrameLayout mProgressContainer;
    private String mPicUri;
    public static final String INTENT_KEY_CAMERA_PIC = CrimeCameraFragment.class.getName() + ".intent.key.camera.pic";

    public static CrimeCameraFragment newInstance() {
        Bundle args = new Bundle();

        CrimeCameraFragment fragment = new CrimeCameraFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println(">>>>>>>>>>>>>>" + TAG + ", onCreate");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        System.out.println(">>>>>>>>>>>>>>" + TAG + ", onCreateView");
        View view = inflater.inflate(R.layout.fragment_camera, container, false);

        bindListeners(view);
        return view;
    }

    @SuppressWarnings("deprecation")
    private void bindListeners(View view) {
        mSurfaceView = (SurfaceView) view.findViewById(R.id.crime_camera_surface);
        mTakeBtn = (Button) view.findViewById(R.id.take_btn);
        mProgressContainer = (FrameLayout) view.findViewById(R.id.camera_progress_container);

        SurfaceHolder holder = mSurfaceView.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.addCallback(new SurfaceHolder.Callback() {//surface通过holder callback，添加surface客户端
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    if (mCamera != null) {
                        mCamera.setPreviewDisplay(holder);//连接holder
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Error! cannot set camera display", e);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mCamera == null) return;

                setCameraSize(width, height);//设置camera preview和picture size
                try {
                    mCamera.startPreview();//启动preview
                } catch (Exception e) {
                    Log.e(TAG, "Count not start camera preview !", e);
                    mCamera.release();
                    mCamera = null;
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mCamera != null) {
                    mCamera.stopPreview();//停止preview
                }
            }
        });

        mTakeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCamera != null) {
                    mCamera.takePicture(
                            new Camera.ShutterCallback() {
                                @Override
                                public void onShutter() {
                                    mProgressContainer.setVisibility(View.VISIBLE);
                                }
                            }, null,
                            new Camera.PictureCallback() {
                                @Override
                                public void onPictureTaken(byte[] data, Camera camera) {
                                    String picFilename = UUID.randomUUID().toString().concat(".jpg");
                                    BufferedOutputStream bos = null;
                                    boolean success = false;
                                    try {
                                        FileOutputStream fos = getActivity().openFileOutput(picFilename, Context.MODE_PRIVATE);
                                        bos = new BufferedOutputStream(fos);
                                        bos.write(data);
                                        success = true;
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    } finally {
                                        if (bos != null) {
                                            try {
                                                bos.close();
                                                bos = null;
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                    if(success) {
                                        Log.i(TAG, "拍照已保存！");
                                        mPicUri = picFilename;
                                    } else {
                                        String errmsg = "拍照保存失败！";
                                        Log.e(TAG, errmsg);
                                        Toast.makeText(getActivity(), errmsg, Toast.LENGTH_SHORT);
                                    }
                                    sendResult(success);

                                }
                            });
                }
            }
        });
    }

    private void sendResult(boolean success) {
        if(success) {
            Intent intent = new Intent();
            intent.putExtra(INTENT_KEY_CAMERA_PIC, mPicUri);
            getActivity().setResult(Activity.RESULT_OK, intent);
        } else {
            getActivity().setResult(Activity.RESULT_CANCELED);
        }
        getActivity().finish();
    }

    private void setCameraSize(final int width, final int height) {
        //比较surface的width和height，从getSupportedPreviewSizes中，选取Camera支持的最佳尺寸作为previewSize
        //获取保存图片的大小pictureSize

        class A {//算法
            Camera.Size getBestSize(List<Camera.Size> sizes, int w, int h) {
                Camera.Size largestSize = mCamera.new Size(0, 0);
                for (Camera.Size size : sizes) {
                    if (size.width * size.height > largestSize.width * largestSize.height) {
                        largestSize = size;
                    }
                }
                return largestSize;
            }
        }
        A a = new A();
        Camera.Parameters parameters = mCamera.getParameters();
        Camera.Size bestPreviewSize = a.getBestSize(parameters.getSupportedPreviewSizes(), width, height);
        Camera.Size bestPictureSize = a.getBestSize(parameters.getSupportedPictureSizes(), width, height);
        parameters.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height);
        parameters.setPictureSize(bestPictureSize.width, bestPictureSize.height);
        mCamera.setParameters(parameters);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out.println(">>>>>>>>>>>>>>" + TAG + ", onActivityResult");

    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println(">>>>>>>>>>>>>>" + TAG + ", onResume");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            mCamera = Camera.open(0);
        } else {
            mCamera = Camera.open();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println(">>>>>>>>>>>>>>" + TAG + ", onPause");

        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
    }
}
